<template>
  <ContentWrap>
    <div class="btnWrap routeHeader">
      <div>
        <el-button @click="saveData" type="primary" v-hasPermi="['order:marketing-order-info:save']">保存</el-button>
        <el-button @click="submitData" type="primary" v-hasPermi="['order:marketing-order-info:submit']">提交</el-button>
        <el-button @click="close">关闭</el-button>
      </div>
    </div>
    <div class="btnWrap">
      <el-button @click="addRow" type="primary" v-if="route.query.type === 'create'"
        >新增行</el-button
      >
    </div>
  </ContentWrap>
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :height="tableHeight" border>
      <el-table-column type="index" width="55" label="序号" align="center" fixed="left"/>
      <!-- 列定义 -->
      <el-table-column align="left" width="180" :class="'custom-header'">
        <template #header>
          <span style="color: red">*</span>
          <span>订单号</span>
        </template>
        <template #default="scope">
          <el-input
            v-model="scope.row.orderNumber"
            @blur="checkId(scope.$index)"
            :error-message="state.idError"
            class="!w-140px"
            :disabled="route.query.type != 'create'"
          />
        </template>
      </el-table-column>
      <el-table-column align="left" width="180">
        <template #header>
          <span style="color: red">*</span>
          <span>订单类型</span>
        </template>
        <template #default="scope">
          <el-select
            v-model="scope.row.dictOrderType"
            placeholder="请选择订单类型"
            required
            class="!w-140px"
          >
            <el-option
              v-for="(dict, index) in getIntDictOptions(DICT_TYPE.MARKET_ORDER_TYPE)"
              :key="index"
              :label="dict.label"
              :value="dict.value"
              :disabled="disableOption(dict.value)"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="left" width="180">
        <template #header>
          <span style="color: red">*</span>
          <span>业务类型</span>
        </template>
        <template #default="scope">
          <el-select
            v-model="scope.row.dictBusinessType"
            placeholder="请选择业务类型"
            class="!w-140px"
          >
            <el-option
              v-for="(dict, index) in getIntDictOptions(DICT_TYPE.BUSINESS_TYPE)"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="left" width="180">
        <template #header>
          <span style="color: red">*</span>
          <span>销售类型</span>
        </template>
        <template #default="scope">
          <el-select v-model="scope.row.dictSaleType" placeholder="请选择销售类型" class="!w-140px">
            <el-option
              v-for="(dict, index) in getIntDictOptions(DICT_TYPE.SALE_TYPE)"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="left" width="180">
        <template #header>
          <span style="color: red">*</span>
          <span>客户简称</span>
        </template>
        <template #default="scope">
          <div class="select-wrapper">
            <el-select
              v-model="scope.row.customerName"
              placeholder="请选择客户简称"
              class="!w-140px"
              filterable
              remote
              :remote-method="filterOptions"
              @change="handleChange(scope.$index)"
            >
              <el-option
                v-for="channel in filteredOptions"
                :key="channel.customerCode"
                :value="channel.customerCode"
                :label="channel.customerName"
              />
            </el-select>
            <span class="search-icon" @click="handleSearch(scope.$index)">
              <Icon icon="ep:search" />
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="left" width="180">
        <template #header>
          <span style="color: red">*</span>
          <span>客户代码</span>
        </template>
        <template #default="scope">
          <span>{{ scope.row.customerCode }}</span>
        </template>
      </el-table-column>
      <el-table-column align="left" width="180">
        <template #header>
          <span style="color: red">*</span>
          <span>销售部门</span>
        </template>
        <template #default="scope">
          <span>{{ scope.row.salesDepartment }}</span>
        </template>
      </el-table-column>
      <el-table-column align="left" width="180">
        <template #header>
          <span style="color: red">*</span>
          <span>合同日期</span>
        </template>
        <template #default="scope">
          <el-date-picker
            v-model="scope.row.contractDate"
            type="date"
            placeholder="请选择合同日期"
            style="width: 150px"
            class="!w-140px"
            value-format="YYYY-MM-DD"
          />
        </template>
      </el-table-column>
      <el-table-column label="订单日期" align="left" width="180">
        <template #default="scope">
          {{ scope.row.orderDate }}
        </template>
      </el-table-column>
      <el-table-column label="业务员" align="left" width="180">
        <template #default="scope">
          {{ scope.row.salesperson }}
        </template>
      </el-table-column>
      <el-table-column label="税率" align="left" width="180">
        <template #default="scope">
          <el-input
            v-model="scope.row.taxRate"
            type="number"
            :min="0"
            :max="100"
            class="!w-140px"
          />
        </template>
      </el-table-column>
      <el-table-column label="汇率" align="left" width="180">
        <template #default="scope">
          <el-input
            v-model="scope.row.exchangeRate"
            :disabled="scope.row.editable"
            type="number"
            :min="0"
            :max="100"
            class="!w-140px"
          />
        </template>
      </el-table-column>
      <el-table-column label="付款条件" align="left" width="180">
        <template #default="scope">
          <el-input
            v-model="scope.row.paymentConditions"
            :disabled="scope.row.editable"
            class="!w-140px"
          />
        </template>
      </el-table-column>
      <el-table-column label="商务合同" align="left" width="180">
        <template #default="scope">
          <UploadFileAdd
            v-model="scope.row.fileList"
            :isShowTip="false"
            :limit="1"
            :fileSize="200"
            :fileType="['pdf', 'png', 'jpg']"
            :index="scope.$index"
            @click="uploadFile(scope.$index)"
            @update:modelValue="uploadFileRes"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="left" width="180">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MARKET_ORDER_STATUS" :value="scope.row.dictOrderStatus" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" width="180">
        <template #default="scope">
          <el-input v-model="scope.row.remark" :disabled="scope.row.editable" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="110" fixed="right">
        <template #default="scope">
          <!-- 删除按钮 -->
          <el-button
            v-if="route.query.type === 'create'"
            link
            type="danger"
            @click="deleteRow(scope.$index)"
            >删除行</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
  <!-- 客户档案列表 -->
  <CustomerProfile ref="formRef" @success="addData" />
</template>

<script lang="ts" setup>
  import { useRoute } from 'vue-router'
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import * as MarketingOrderInfoApi from '@/api/orderManagement/marketingOrderInfo'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import CustomerProfile from './customerProfile.vue'
  const tagsViewStore = useTagsViewStore()
  const routes = useRouter() // 路由
  const route = useRoute()
  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗
  // const queryFormRef = ref() // 搜索的表单
  const { push } = useRouter()
  const loading = ref(true)
  const list = ref<any>([])
  const formLoading = ref(false)
  const state = reactive({
    idError: ''
  })
  let title = ref('新增订单信息')
  const changeIndex = ref(0)
  const fileList = ref([])
  // const nameError = ref('')
  const tenantOptions = ref<any>([])
  let filteredOptions = ref<any>([])
  //模糊查询
  const filterOptions = async (query) => {
    if (query) {
      filteredOptions = await tenantOptions.value.filter((option) =>
        option.customerName.includes(query)
      )
    }
  }
  const disableOption = (value) => {
    if (value == '60') {
      return true
    } else {
      return false
    }
  }
  const formRef = ref()
  //搜索图标
  const handleSearch = async (index) => {
    formRef.value.open(index, list.value[index].customerCode)
  }
  const handleChange = async (index) => {
    for (let i = 0; i < tenantOptions.value.length; i++) {
      if (tenantOptions.value[i].customerCode == list.value[index].customerName) {
        list.value[index].customerCode = tenantOptions.value[i].customerCode
        list.value[index].salesDepartment = tenantOptions.value[i].salesDepartment
        list.value[index].salesperson = tenantOptions.value[i].salesperson
        list.value[index].taxRate = tenantOptions.value[i].taxRate
        list.value[index].exchangeRate = tenantOptions.value[i].exchangeRate
        list.value[index].paymentConditions = tenantOptions.value[i].paymentConditions
        list.value[index].paymentName = tenantOptions.value[i].paymentName
        list.value[index].salespersonNumber = tenantOptions.value[i].salespersonNumber
      }
    }
  }
  const addData = async (data) => {
    list.value[data.index.value].customerName = data.list[0].customerName
    list.value[data.index.value].customerCode = data.list[0].customerCode
    list.value[data.index.value].salesDepartment = data.list[0].salesDepartment
    list.value[data.index.value].customerName = data.list[0].customerName
    list.value[data.index.value].salesperson = data.list[0].salesperson
    list.value[data.index.value].taxRate = data.list[0].taxRate
    list.value[data.index.value].exchangeRate = data.list[0].exchangeRate
    list.value[data.index.value].paymentConditions = data.list[0].paymentConditions
  }
  const getList = async () => {
    loading.value = true
    try {
      // 请求数据的逻辑
    } finally {
      loading.value = false
    }
  }
  const addRow = () => {
    let today = new Date()
    let year = today.getFullYear()
    let month = (today.getMonth() + 1).toString().padStart(2, '0')
    let date = today.getDate().toString().padStart(2, '0')
    let dateString = year + '-' + month + '-' + date
    const newRow = {
      orderNumber: undefined,
      dictOrderType: undefined,
      dictBusinessType: undefined,
      dictSaleType: undefined,
      customerName: undefined,
      customerCode: undefined,
      salesDepartment: undefined,
      contractDate: undefined,
      orderDate: dateString,
      salesperson: undefined,
      taxRate: undefined,
      exchangeRate: undefined,
      paymentConditions: undefined,
      dictChangeType: undefined,
      orderVersion: undefined,
      orderChangePerson: undefined,
      orderChangeDate: undefined,
      remark: undefined,
      businessContractUrl: undefined,
      businessContractName: undefined,
      dictOrderStatus: undefined,
      id: undefined,
      filePath: '',
      fileName: '',
      fileList: []
    }
    list.value.push(newRow)
  }

  const deleteRow = (index: number) => {
    list.value.splice(index, 1)
  }

  //必填校验
  const check = async () => {
    let data = await list.value
    if (data.length) {
      for (let i = 0; i < data.length; i++) {
        if (!data[i].orderNumber) {
          message.warning(t('订单号不能为空'))
          return false
        }
        if (!data[i].dictOrderType) {
          message.warning(t('订单类型不能为空'))
          return false
        }
        if (!data[i].dictBusinessType) {
          message.warning(t('业务类型不能为空'))
          return false
        }
        if (!data[i].dictSaleType) {
          message.warning(t('销售类型不能为空'))
          return false
        }
        if (!data[i].customerName) {
          message.warning(t('客户简称不能为空'))
          return false
        }
        if (!data[i].salesDepartment) {
          message.warning(t('销售部门不能为空'))
          return false
        }
        if (!data[i].contractDate) {
          message.warning(t('合同日期不能为空'))
          return false
        }
        // if (!data[i].orderDate) {
        //   message.warning(t('订单日期不能为空'))
        //   return false
        // }
        if (!data[i].filePath) {
          message.warning(t('商务合同不能为空'))
          return false
        }
      }
    } else {
      message.warning(t('请新增行'))
      return false
    }

    return true
  }
  /**保存 */
  const saveData = async () => {
    const isFlag = await check()
    if (isFlag) {
      try {
        loading.value = true
        let type = route.query.type
        if (type === 'create') {
          let reqData = {
            submitFlag: 1,
            marketingOrders: list.value
          }
          await MarketingOrderInfoApi.createMarketingOrderInfo(reqData)
          message.success(t('common.createSuccess'))
          tagsViewStore.delView(routes.currentRoute.value)
          push('/orderManagement/orderManagement/marketing/info')
        } else {
          list.value[0].submitFlag = 1
          let reqData = list.value[0]
          await MarketingOrderInfoApi.updateMarketingOrderInfo(reqData)
          message.success(t('common.updateSuccess'))
          tagsViewStore.delView(routes.currentRoute.value)
          push('/orderManagement/orderManagement/marketing/info')
        }
      } finally {
        loading.value = false
      }
    }
  }
  /**提交 */
  const submitData = async () => {
    const isFlag = await check()
    if (isFlag) {
      loading.value = true
      try {
        let type = route.query.type
        if (type === 'create') {
          let reqData = {
            submitFlag: 2,
            marketingOrders: list.value
          }
          await MarketingOrderInfoApi.createMarketingOrderInfo(reqData)
          message.success(t('common.createSuccess'))
          tagsViewStore.delView(routes.currentRoute.value)
          push('/orderManagement/orderManagement/marketing/info')
        } else {
          list.value[0].submitFlag = 2
          let reqData = list.value[0]
          await MarketingOrderInfoApi.updateMarketingOrderInfo(reqData)
          message.success(t('common.updateSuccess'))
          tagsViewStore.delView(routes.currentRoute.value)
          push('/orderManagement/orderManagement/marketing/info')
        }
      } finally {
        loading.value = false
      }
    }
  }
  /**关闭 */
  const close = () => {
    tagsViewStore.delView(routes.currentRoute.value)
    push('/orderManagement/orderManagement/marketing/info')
  }
  //获取订单信息
  const getDetail = async (id) => {
    const data = await MarketingOrderInfoApi.getMarketingOrderInfo(id)
    if (data.fileName) {
      let json = {
        name: data.fileName,
        url: data.filePath
      }
      let fileList = ref<any>([])
      fileList.value.push(json)
      data.fileList = fileList
      list.value.push(data)
    } else {
      let fileList = ref<any>([])
      data.fileList = fileList
      list.value.push(data)
    }
  }
  const checkId = (index: number) => {
    if (!list.value[index].orderNumber) {
      state.idError = '订单号必须填写'
    }
  }
  /**上传附件 */
  const uploadFile = async (index) => {
    changeIndex.value = await index
  }
  /**文件上传返回 */
  const uploadFileRes = async (data) => {
    const res = await JSON.parse(data)
    if (res.length > 0) {
      let index = res[0].index
      if (JSON.parse(data).length) {
        list.value[index].filePath = res[0].url
        list.value[index].fileName = res[0].name
      } else {
        fileList.value = []
        list.value[index].filePath = ''
        list.value[index].fileName = ''
      }
    } else {
      list.value[changeIndex.value].tblFilePath = ''
      list.value[changeIndex.value].tblFileName = ''
    }
  }
  const contentHeight = ref(0)
  const refreshData = async () => {
    formLoading.value = true
    contentHeight.value = document.body.clientHeight - 127
    formLoading.value = false
  }
  //获取客户档案列表
  const getCustomerProfileList = async () => {
    let params = {}
    const data = await MarketingOrderInfoApi.getCustomerProfileList(params)
    tenantOptions.value = data.list
  }
  // 初始化
  const tableHeight = ref(0)
  onMounted(async () => {
    tableHeight.value = document.body.clientHeight - 132 - 140
    refreshData()
    let type = route.query.type
    if (type === 'create') {
      title.value = '新增订单信息'
    } else {
      title.value = '编辑订单信息'
    }
    if (route.query.id != 'undefined') {
      getDetail(route.query.id)
    }
    await getList()
    await getCustomerProfileList()
  })
</script>
<style lang="scss" scoped>
  .contentView {
    padding: 10px;
    background: #fff;
  }
  .tableView {
    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
      cursor: default;
      .el-input__inner {
        cursor: default !important;
        text-align: center;
      }
    }
  }
  .btnWrap {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  .el-table .custom-header::before {
    content: '*';
    color: red;
    margin-right: 4px; /* 根据需要调整小红星与字段的位置 */
  }
  .dropdown-width {
    width: 50px !important;
  }
  :deep(.el-form .el-input, .el-form .el-input__wrapper, .el-form .el-textarea) {
    width: 100% !important;
  }
  .select-wrapper {
    display: flex;
    align-items: center;
  }

  .search-icon {
    margin-left: -24px; /* 这里的 -24px 是根据 Icon 的宽度进行调整的 */
    cursor: pointer;
    margin-top: 5px;
  }
</style>
